package com.sinosoft.sinopay.web.batch.biz.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.sinosoft.sinocloud.platform.base.SinoBaseService;
import com.sinosoft.sinocloud.platform.common.util.DateUtil;
import com.sinosoft.sinocloud.platform.common.util.StringUtil;
import com.sinosoft.sinopay.api.common.dto.pay.PayAccountInfoDTO;
import com.sinosoft.sinopay.api.common.dto.pay.PaymentInfoDetailDTO;
import com.sinosoft.sinopay.api.pay.service.BatchpayApiService;
import com.sinosoft.sinopay.customer.facade.CustomerFacadeService;
import com.sinosoft.sinopay.payrules.dto.PayRouteCheckDTO;
import com.sinosoft.sinopay.payrules.facade.PayRuleFacade;
import com.sinosoft.sinopay.paytrade.dto.PayTradeSearchDTO;
import com.sinosoft.sinopay.paytrade.dto.PaymentTradeBatchDTO;
import com.sinosoft.sinopay.paytrade.dto.PaymentTradeReqDTO;
import com.sinosoft.sinopay.paytrade.facade.PaymentTradeFacadeService;
import com.sinosoft.sinopay.paytrade.facade.PaymentTradeQueryFacadeService;
import com.sinosoft.sinopay.web.batch.biz.service.BatchPayService;
import com.sinosoft.sinopay.web.batch.biz.service.PaymentBatchService;
import com.sinosoft.sinopay.web.batch.dto.BatchDetailInfo;
import com.sinosoft.sinopay.web.batch.dto.BatchInfo;
import com.sinosoft.sinopay.web.batch.dto.RequestBaseXml;
import com.sinosoft.sinopay.web.batch.dto.RequestHead;
import com.sinosoft.sinopay.web.batch.dto.RequestSearchBaseXml;
import com.sinosoft.sinopay.web.batch.dto.ResultInfo;
import com.sinosoft.sinopay.web.batch.dto.SearchDetailInfo;
import com.sinosoft.sinopay.web.batch.dto.SearchInfo;
import com.sinosoft.sinopay.web.batch.dto.SearchResultDetail;
import com.sinosoft.sinopay.web.batch.dto.SearchResultInfo;

/**
 * 【 批量数据验证存储实现 】
 *
 * @author chenzhiheng
 * @version V1.0
 * @date 16/12/29
 */
@Service
public class BatchPayServiceImpl extends SinoBaseService implements BatchPayService{

    @Autowired
    private PaymentBatchService paymentCacpsService;

    @Autowired
    private PaymentTradeFacadeService paymentTradeFacadeService;

    @Autowired
    private PaymentTradeQueryFacadeService paymentTradeQueryFacadeService;

    @Autowired
    private PayRuleFacade payRuleFacade;

    @Autowired
    private BatchpayApiService batchpayApiService;

    @Autowired
    private CustomerFacadeService customerFacadeService;

    /**
     * 处理批量数据实现
     *@return
     */
    @Override
    public ResultInfo callBizService(RequestBaseXml requestObj) throws Exception {
        RequestHead tHead = requestObj.getBatchTransHead();
        BatchInfo batchInfo = requestObj.getTransInfo();
        String merchantCode = tHead.getMerchantCode();
        String payCode = tHead.getPayType();
        String bankCode = batchInfo.getBankCode();
        PaymentTradeReqDTO batchPayInfo = new PaymentTradeReqDTO();

        if (StringUtil.isBlank(bankCode)) {
            //如果没有交易银行编码
            PayRouteCheckDTO payRouteCheckDTO = new PayRouteCheckDTO();
            payRouteCheckDTO.setPayAmount(batchInfo.getTotalSum());
            payRouteCheckDTO.setPayType(tHead.getPayType());
            PayRouteCheckDTO resultPayRoute = payRuleFacade.payRoute(payRouteCheckDTO);
            bankCode = resultPayRoute.getThirdpayCode();
            batchPayInfo.setThirdpayCode(bankCode);
        } else {
            batchPayInfo.setPayBankCode(batchInfo.getBankCode());
        }
        if (StringUtil.isBlank(batchInfo.getTotalItem())) {
            throw new Exception("总条数不可为空");
        } else {
            batchPayInfo.setTradeNum(Integer.parseInt(batchInfo.getTotalItem()));
        }
        if (StringUtil.isBlank(batchInfo.getTotalSum().toString())) {
            throw new Exception("总金额不可为空");
        } else {
            batchPayInfo.setSumAmount(batchInfo.getTotalSum());
        }
        if (StringUtil.isBlank(merchantCode)) {
            throw new Exception("商户编号不可为空");
        } else {
            batchPayInfo.setMerchantCode(merchantCode);
        }
        if (StringUtil.isBlank(payCode)) {
            throw new Exception("支付类型不可为空");
        } else {
            batchPayInfo.setPayFlag(payCode);
        }
        //新增一条批次信息返回批次号
        batchPayInfo.setCreatorId(1);
        batchPayInfo.setPayChannelId(Integer.parseInt(bankCode));
        String batchNo = paymentTradeFacadeService.addTransOrderBatchInfo(batchPayInfo);
        logger.info("生成批次号为："+batchNo);
        if(batchNo == null && "".equals(batchNo)){
            throw new Exception("新增一条批次失败");
        }
        //插入支付交易表
        List<BatchDetailInfo> batchDetailInfoList = batchInfo.getTransDetailInfo();
        PaymentTradeReqDTO paymentTradeReqDTO = new PaymentTradeReqDTO();
        PaymentTradeReqDTO paymentTradeReqRela = new PaymentTradeReqDTO();
        PayAccountInfoDTO payAccountInfoDTO = new PayAccountInfoDTO();
        for(int i = 0;i < batchDetailInfoList.size(); i++) {
            //校验订单重复性
            //paymentCacpsService.checkRepeatRequest(batchPayInfo.getMerchantCode(),batchDetailInfoList.get(i).getSerialNo());
            //写入交易表数据
            paymentTradeReqDTO.setSerialNo(batchDetailInfoList.get(i).getSerialNo());
            paymentTradeReqDTO.setBizNo(batchDetailInfoList.get(i).getBizNo());
            paymentTradeReqDTO.setBatchNo(batchNo);
            paymentTradeReqDTO.setMerchantCode(tHead.getMerchantCode());
            paymentTradeReqDTO.setThirdpayCode(batchInfo.getBankCode());
            paymentTradeReqDTO.setBizType(tHead.getBatchBizType());
            paymentTradeReqDTO.setPayWay(batchDetailInfoList.get(i).getBizType());
            paymentTradeReqDTO.setPayFlag(payCode);
            paymentTradeReqDTO.setThirdpayCode(bankCode);
            paymentTradeReqDTO.setPayStatus("0");//准备发送批量
            paymentTradeReqDTO.setPayDate(DateUtil.getCurrentDate());
            paymentTradeReqDTO.setPayAmount(batchDetailInfoList.get(i).getPayAmount());
            paymentTradeReqDTO.setPayAccountName(batchDetailInfoList.get(i).getAccountName());
            paymentTradeReqDTO.setPayBankCode(batchDetailInfoList.get(i).getBankCode());
            paymentTradeReqDTO.setPayBankName(batchDetailInfoList.get(i).getBankName());
            paymentTradeReqDTO.setPayAccountNo(batchDetailInfoList.get(i).getAccountNo());
            paymentTradeReqDTO.setPayAccountMobile(batchDetailInfoList.get(i).getMobile());
            int resultPayment = paymentTradeFacadeService.addPaymentInfo(paymentTradeReqDTO);
            //插入交易支付关系表
            paymentTradeReqRela.setBatchNo(batchNo);
            paymentTradeReqRela.setTradeId(resultPayment);
            paymentTradeReqRela.setPayChannelId(Integer.parseInt(batchInfo.getBankCode()));
            int resultRela = paymentTradeFacadeService.addTransePayRelate(paymentTradeReqRela);
            if(resultRela != 1){
                throw new Exception("新增支付交易关系表失败");
            }
            //插入客户信息表
//            payAccountInfoDTO.setBankName(batchDetailInfoList.get(i).getBankName());
//            payAccountInfoDTO.setAccountName(batchDetailInfoList.get(i).getAccountName());
//            payAccountInfoDTO.setAccountNo(batchDetailInfoList.get(i).getAccountNo());
//            payAccountInfoDTO.setAccountType(batchDetailInfoList.get(i).getBizType());
//            payAccountInfoDTO.setBankCode(batchDetailInfoList.get(i).getBankCode());
//            payAccountInfoDTO.setMobile(batchDetailInfoList.get(i).getMobeil());
//            int resultCustomer = customerFacadeService.saveCustomerPayAccountInfo(payAccountInfoDTO);
//            if(resultCustomer < 1){
//                throw new Exception("新增客户信息失败");
//            }
        }
        //非通联批量生成总表信息
        if(!"3333".equals(bankCode)) {
            //插入支付总表信息
            PaymentTradeBatchDTO paymentTradeBatchDTO = new PaymentTradeBatchDTO();
            paymentTradeBatchDTO.setPayBatchNo(batchNo);
            paymentTradeBatchDTO.setIfStartDate(DateUtil.getCurrentDate());
            paymentTradeBatchDTO.setPayFlag(payCode);
            paymentTradeBatchDTO.setPayChannelId(Integer.parseInt(batchInfo.getBankCode()));
            paymentTradeBatchDTO.setTradeAmount(batchInfo.getTotalSum());
            paymentTradeBatchDTO.setTradeNum(Integer.parseInt(batchInfo.getTotalItem()));
            int resultBatch = paymentTradeFacadeService.addBulkPaymentInfo(paymentTradeBatchDTO);
            if (resultBatch != 1) {
                throw new Exception("新增一条支付总表信息失败");
            }
        }else{
            //通联批量直接调用API
            batchpayApiService.batchPay(bankCode);
        }
        //封装返回报文体
        ResultInfo tResult = new ResultInfo();
        tResult.setBatchNo(batchNo);
        return tResult;
    }

    /**
     * 批量查询接口实现
     *@return
     */
    @Override
    public SearchResultInfo searchBizService(RequestSearchBaseXml requestSearchBaseXml) throws  Exception{
        SearchInfo searchInfo = requestSearchBaseXml.getQueryResultInfo();
        String batchNo = searchInfo.getBatchNo();
        List<SearchDetailInfo> searchDetailInfos = searchInfo.getQueryDetailInfo();
        PayTradeSearchDTO payTradeSearchDTO = new PayTradeSearchDTO();
        if (StringUtil.isBlank(batchNo)) {
            throw new Exception("批次号不可为空");
        } else {
            payTradeSearchDTO.setBatchNo(batchNo);
        }
        List<SearchResultDetail> searchResultInfoList = new ArrayList<SearchResultDetail>();
        for(int i = 0;i < searchDetailInfos.size(); i++) {
            SearchDetailInfo searchDetailInfo = searchDetailInfos.get(i);
            if (StringUtil.isBlank(searchDetailInfo.getAccountName())) {
                throw new Exception("姓名不可为空");
            } else {
                payTradeSearchDTO.setName(searchDetailInfo.getAccountName());
            }
            if (StringUtil.isBlank(searchDetailInfo.getSerialNo())) {
                throw new Exception("流水号不可为空");
            } else {
                payTradeSearchDTO.setSerialNo(searchDetailInfo.getSerialNo());
            }
            PaymentInfoDetailDTO  paymentInfoDetailDTO= paymentTradeQueryFacadeService.queryBatchResultCode(payTradeSearchDTO);
            if(paymentInfoDetailDTO != null) {
                SearchResultDetail searchResultInfo = new SearchResultDetail();
                searchResultInfo.setBatchNo(batchNo);
                searchResultInfo.setAccountName(paymentInfoDetailDTO.getAccountName());
                searchResultInfo.setSerialNo(paymentInfoDetailDTO.getSerialNo());
                searchResultInfo.setBizType(paymentInfoDetailDTO.getPayType());
                searchResultInfo.setResultCode(paymentInfoDetailDTO.getReturnCode());
                searchResultInfo.setResultMsg(paymentInfoDetailDTO.getReturnMsg());
                searchResultInfoList.add(searchResultInfo);
            }else{
                SearchResultDetail searchResultInfo = new SearchResultDetail();
                searchResultInfo.setBatchNo(batchNo);
                searchResultInfo.setAccountName(payTradeSearchDTO.getName());
                searchResultInfo.setSerialNo(payTradeSearchDTO.getSerialNo());
                searchResultInfo.setBizType("");
                searchResultInfo.setResultCode("04");
                searchResultInfo.setResultMsg("无数据返回");
                searchResultInfoList.add(searchResultInfo);
            }
        }
        SearchResultInfo searchResultInfo = new SearchResultInfo();
        searchResultInfo.setSearchResultDetailList(searchResultInfoList);
        return searchResultInfo;
    }

}
